local O = {}



--- 获得真正的主将/副将（而非暗将）
---@param player Player
---@param isDeputy bool
---@return string
O.getActualGeneral = function(player, isDeputy)
  if isDeputy then
    return player.deputyGeneral == "anjiang" and player:getMark("__heg_deputy") or player.deputyGeneral or ""
  else
    return player.general == "anjiang" and player:getMark("__heg_general") or player.general
  end
end



--- 变更武将牌
---@param room Room
---@param player ServerPlayer
---@param isMain bool @ 是否为主将，默认副将
---@param num integer @ 选将数量，默认为3
---@param isHidden boolean
O.transformGenerals = function(room, player, isMain, num,  isHidden)
   local data = {
    isMain = isMain,
    isHidden = isHidden,
    num = num,
  }
  if room.logic:trigger("fk.GeneralTransforming", player, data) then return false end
  isMain = data.isMain
  isHidden = data.isHidden
  num = data.num
  local orig = isMain and player.general or player.deputyGeneral
  num = num or 3
  if not orig then return false end
  if orig == "anjiang" then
    player:revealGeneral(not isMain, true)
    orig = isMain and player.general or player.deputyGeneral
  end
  local existingGenerals = {}
  for _, p in ipairs(room.players) do
    table.insert(existingGenerals, O.getActualGeneral(p, false))
    table.insert(existingGenerals, O.getActualGeneral(p, true))
  end
  local kingdom = player:getMark("__heg_kingdom")
  if kingdom == "wild" then
    kingdom = player:getMark("__heg_init_kingdom")
  end
  local generals = room:findGenerals(function(g)
    return Fk.generals[g].kingdom == kingdom or Fk.generals[g].subkingdom== kingdom
  end, num)
  local general = room:askForGeneral(player, generals, 1, true) ---@type string
  table.removeOne(generals, general)
  table.insert(generals, orig)
  room:returnToGeneralPile(generals)
  room:changeHero(player, general, false, not isMain, not isHidden, false, false)
  if isHidden then
    player:hideGeneral(not isMain)
    room:sendLog{
      type = "#ChangeHiddenGeneral",
      from = player.id,
    }
  end
  room:setPlayerMark(player, isMain and "__heg_general" or "__heg_deputy", general)
  room.logic:trigger("fk.GeneralTransformed", player, orig)
end
Fk:loadTranslationTable{
  ["#ChangeHiddenGeneral"] = "%from 变更了副将（暗置）",
}

  return O